module RatingsHelper
  def ratings_type_filter
    type_filter = []
    
    types = ["all"] + RateableObject::TYPES
    types.each do |type|
      type_display = type == "all" ? type : type.pluralize
      type_display.capitalize!
      type_filter << 
        if (type == "All" && @type.nil?) || (type == @type)
          type_display
        else
          ratings_load(type_display, ratings_content_url(:type => (type == "all" ? nil : type), :creator => nil, :genre => nil))
        end
    end
    
    type_filter * " | "
  end
  
  def rating_display_with_link(obj)
    url = obj.url.to_s
    url = "http://#{url}" if url[0,7] != "http://"
    obj.url.blank? ? 
      h(obj.name) : 
      link_to(h(obj.name), url, :target => "_blank")
  end
  
  def ratings_list_header
    header = ""
    
    header += 
      @type.nil? ?
        %Q( <td class="header" style="width: 70px;">#{ratings_load("Type", header_url("rateable_type", "ASC"))}</td> ) :
        %Q( <td class="header" style="width: 1px;"></td> )
    
    header += %Q(
        <td class="header" style="width: 135px;">
          #{ratings_load("Name", header_url("name", "ASC"))}</td>
        <td class="header" style="width: #{@type == "website" ? 1 : 115}px;">
          #{ratings_load(association_display, header_url("creator", "ASC"))}</td>
        <td class="header" style="width: 95px;">
          #{ratings_load("Genre", header_url("genre", "ASC"))}</td>
        <td class="header" style="width: 40px;">
          #{ratings_load("My", header_url("my_score", "DESC"))}</td>
        <td class="header" style="width: 40px;">
          #{ratings_load("Avg", header_url("average_score", "DESC"))}</td>
        <td class="header" style="width: 40px;">
          #{ratings_load("Your", header_url("your_score", "DESC"))}</td>
        <td class="header" style="width: 70px;">
          #{ratings_load("Added", header_url("created_at", "DESC"))}</td>
      )
  end
  
  def header_url sort_by, sort_order
    ratings_content_url(:type => @type, :order => get_order(sort_by, sort_order))
  end
  
  def get_order sort_by, sort_order = "ASC"
    default_asc = (sort_order == "ASC")
    
    # Currently already this sort, flip the sort order
    if params[:order].to_s.index(sort_by) == 0
      current_sort_order = params[:order].to_s.split(' ')[1]
      "#{sort_by} #{current_sort_order == "ASC" ? "DESC" : "ASC"}"
    else 
      "#{sort_by} #{default_asc ? "ASC" : "DESC"}"
    end
  end
  
  def ratings_load display, link
    link_to_remote(
      display,
      :url      => link, 
      :method   => "get", 
      :before   => "Ratings.startLoad();",
      :complete => "Ratings.stopLoad();",
      :with     => "'guid=' + Guid.get()") 
  end
  
  def association_display
    case @type
      when "song"
        "Singer / Band"
      when "book"
        "Author"
      when "film"
        "Director"
      when "website"
        ""
      else
        "By"
    end
  end
end